// order-detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: ' 王俊凯',
    address: '广东省广州市天河区体育中心28号天河城广场北座1号楼608',
    phone: '13356788996',
    status: '待发货',
    // num:'1',
    active_ :'1',
    coupon_id: -1,
    coupon: -1,
    money: '0',
    order_id: '89757',
    time: '2017-8-1 15:30',
    goods: [
      {
        name: '法国·AOP  雕花干红葡萄酒 750ml',
        url: 'http://img0.imgtn.bdimg.com/it/u=1256543677,1353976295&fm=26&gp=0.jpg',
        price: '280',
        num: '1'
      },
      {
        name: '法国·AOP  雕花干红葡萄酒 750ml',
        url: 'http://img0.imgtn.bdimg.com/it/u=1256543677,1353976295&fm=26&gp=0.jpg',
        price: '280',
        num: '1'
      }
    ],
    item: [
      {
        label: '商品总额',
        value: '￥560'
      },
      {
        label: '运费',
        value: '+15'
      },
      {
        label: '酒币抵扣5元',
        value: '-5'
      },
      {
        label: '使用优惠券减5元',
        value: '-5'
      },
      {
        label: '总计：',
        value: '￥285'
      }
    ],
    
  },
  
  // 立即购买
  buy_now(price, product_id, is_seckill) {
    wx.showLoading({
      title: '正在加载...',
      mask: true
    })
    let baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      header = getApp().globalData.header,
      // coupon_id = this.data.hasOwnProperty('coupon') && typeof this.data.data.coupon.unused!=null ? this.data.data.coupon.unused[this.data.coupon].coupon_id : '',
      coupon_id = this.data.coupon == -1 ? '' : this.data.data.coupon.unused[this.data.coupon].coupon_id
      // cash = this.data.coupon == -1 ? '' : Number(this.data.data.coupon.unused[this.data.coupon].cash)

    let num = this.data.num || 1,
      self = this;
    
    wx.request({
      url: baseUrl + '/Order/check',
      method: 'GET',
      data: { access_token, price, product_id, num, is_seckill, coupon_id},
      header,
      success: data => {
        wx.hideLoading()
        console.log(666)        
        console.log(data.data.data)
        if (data.data.code == 200) {
          //console.log(typeof data.data.data.is_seckill);
          if (data.data.data.is_seckill == 2){
            console.log('is_seckill 2')
            //let new_integral_price = parseInt(data.data.data.integral_value * data.data.data.list[0].price * data.data.data.list[0].num - 1);
            let pay_price = (parseFloat(data.data.data.pay_price) - this.data.money).toFixed(2)
            if (pay_price <= 0) {
              self.setData({
                pay_price: 0.01
              })
            } else {
              self.setData({
                pay_price: pay_price
              })
            }

            let integral_price = data.data.data.integral_price
            if (integral_price <= 0) {
              self.setData({
                integral_price: 0
              })
            } else {
              self.setData({
                integral_price: integral_price
              })
            }
            self.setData({
              data: data.data.data,
              num: data.data.data.list[0].num,
              price: data.data.data.list[0].price,
              freight_price: data.data.data.freight_price,
              total_price: data.data.data.total_price,
              // pay_price: pay_price,
              coupons_price: data.data.data.coupons_price,
              // cash: cash,
              //new_integral_price: new_integral_price,
              // integral_price: integral_price,
            })
          } else if (data.data.data.is_seckill == 1){ 
            console.log('is_seckill 1')
            //let new_integral_price = parseInt(data.data.data.integral_value * data.data.data.list[0].price * data.data.data.list[0].num - 1);
            let pay_price = (parseFloat(data.data.data.pay_price) - this.data.money).toFixed(2)
            if (pay_price <= 0) {
              self.setData({
                pay_price: 0.01
              })
            } else {
              self.setData({
                pay_price: pay_price
              })
            }

            let integral_price = data.data.data.integral_price
            if (integral_price <= 0) {
              self.setData({
                integral_price: 0
              })
            } else {
              self.setData({
                integral_price: integral_price
              })
            }
            self.setData({
              data: data.data.data,
              num: data.data.data.list[0].num,
              price: data.data.data.list[0].price,
              freight_price: data.data.data.freight_price,
              total_price: data.data.data.total_price,
              pay_price: pay_price,
              coupons_price: data.data.data.coupons_price,
              // cash: cash,
              //new_integral_price: new_integral_price,
              // integral_price: integral_price,
            })
          }
        } else {
          wx.showToast({
            title: data.data.message
          })
        } 
         
        // else if (data.data.code == 400) {
        //   wx.navigateBack({
        //     delta: 1
        //   })
        // }
      }
    })
  },
  // 获取地址
  getAddress(){
    let baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      self = this
    wx.request({
      url: baseUrl + '/Address/index',
      data: { access_token},
      method: 'GET',
      success: data => {
        console.log(data.data.data)
        let list = []
        data.data.data.forEach( value => {
          list.push(value.address + '  ' + value.accept_name + '  ' + value.phone)
        })
        list.push('管理收货地址')
        wx.showActionSheet({
          itemList: list,
          success: res => {
            console.log(res)
            if (res.cancel){
              return
            }
            if(res.tapIndex != list.length-1){
              console.log(res.tapIndex)
              let address = self.data.data
              address.address = data.data.data[res.tapIndex]
              self.setData({
                data:address
              })
            }else{
              wx.navigateTo({
                url: '../address/address',
              })
            }
          }
        })
      }
    })
  },
  //选择购买数量
  computed(e) {
    let type_ = e.currentTarget.dataset.type
    // let index = parseInt(e.currentTarget.dataset.index);
    let num = this.data.data.list[0].num
    
    
    let self =this
    console.log(this.data)
    console.log(this.data.data.list[0].num)
    if (type_ == 'down') {
      if (this.data.num <= 1) {
        this.setData({
          num: '1',
        })
        wx.showToast({
          title: "至少为1",
        })
      }else{
        this.setData({
          num: --this.data.data.list[0].num,
        })
      }
      
    } else if (type_ == 'up' && this.data.num <= this.data.data.list[0].stock) {
      if (this.data.num == this.data.data.list[0].stock) {
        this.setData({
          num: this.data.data.list[0].stock,
        })
        wx.showToast({
          title: "库存不足",
        })
      } else if (this.data.num < this.data.data.list[0].stock){ 
        this.setData({
          num: ++this.data.data.list[0].num,
        })
      }
      
    }
  
    this.caculaeMoney(this.data.num)
    this.getIntegralPrice(this.data.num)

  },
  // 计算商品总额
  caculaeMoney (num) {
    let total_price = 0
    let pay_price = 0
    let coupons_price
    if (this.data.coupons_price==undefined){
      coupons_price = 0
    }else{
      coupons_price = this.data.coupons_price
    }

    console.log('加减总计',this.data)
    total_price = (parseFloat(this.data.data.list[0].price) * parseInt(this.data.num)).toFixed(2)
    pay_price = (total_price * 1 + parseFloat(this.data.data.freight_price) - parseInt(coupons_price) - this.data.money).toFixed(2)
    if (pay_price<=0){
      this.setData({
        total_price: total_price,
        pay_price: 0.01
      })
    }else{
      this.setData({
        total_price,
        pay_price
      })
    }
  },
  // 计算最多抵使用酒币数量
  getIntegralPrice(num){
    // console.log(this.data.data.integral_value)
    // let new_integral_price = parseInt(this.data.data.integral_value * this.data.total_price - 1);
    // this.setData({
    //   new_integral_price: new_integral_price
    // })

    let baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      header = getApp().globalData.header;

    let options = this.data.options,
      price = options.price,
      product_id = options.product_id
    let self = this

    wx.request({
      url: baseUrl + '/Order/check',
      method: 'GET',
      data: { access_token, num, price, product_id},
      header,
      success: data => {
        console.log("计算最多抵使用酒币数量", data.data)
        if(data.data.code==200){
         
          if (data.data.data.integral_price<=0){
            self.setData({
              integral_price: 0
            })
          }else{
            self.setData({
              integral_price: data.data.data.integral_price
            })
          }
        } 
      }
    })

  },
  // 购物车下单
  buy_cart(num, check, car_id) {
    wx.showLoading({
      title: '正在加载...',
      mask: true
    })
    let baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      header = getApp().globalData.header,
      coupon_id = this.data.coupon == -1 ? '' : this.data.data.coupon.unused[this.data.coupon].coupon_id,
      // coupon_id = this.data.hasOwnProperty('coupon') && typeof this.data.data.coupon.unused != null ? this.data.data.coupon.unused[this.data.coupon].coupon_id : '',
      //cash = this.data.coupon == -1 ? '' : Number(this.data.data.coupon.unused[this.data.coupon].cash),
      self = this;
    // let index = parseInt(this.data.index);

    wx.request({
      url: baseUrl + '/Order/check',
      method: 'GET',
      data: { access_token, num, check, car_id, coupon_id},
      header,
      success: data => {
        wx.hideLoading()
        console.log(data.data)
        if(data.data.code==200){
          // let new_integral_price = parseInt(data.data.data.integral_value * data.data.data.list[0].price * data.data.data.list[0].num - 1);
          let pay_price = (parseFloat(data.data.data.pay_price) - this.data.money).toFixed(2)
          if (pay_price <= 0) {
            self.setData({
              pay_price: 0.01
            })
          } else {
            self.setData({
              pay_price: pay_price
            })
          }

          let integral_price = data.data.data.integral_price
          if (integral_price <= 0) {
            self.setData({
              integral_price: 0
            })
          } else {
            self.setData({
              integral_price: integral_price
            })
          }
          self.setData({
            data: data.data.data,
            num: data.data.data.list[0].num,
            price: data.data.data.list[0].price,
            freight_price: data.data.data.freight_price,
            total_price: data.data.data.total_price,
            pay_price: pay_price,
            coupons_price: data.data.data.coupons_price,
            // cash: cash,
            // integral_price: integral_price,
          })
        }else{
          wx.showToast({
            title: data.data.message
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ options })
    if (options.isBuyNow == 'true') {
      var price = options.price,
        product_id = options.product_id
      let self = this
      if (!getApp().globalData.access_token ){
        getApp().setUser(function(){
          return self.buy_now(price, product_id)
        })
     }else{
        self.buy_now(price, product_id)
     }
    }else{
      console.log(666)
      this.buy_cart(options.num, options.check, options.car_id)
    }
  },
  // 输入留言
  messageInput(e){
    this.setData({
      message: e.detail.value
    })
  },
  // 提交
  submit(){
    wx.showLoading({
      title: '正在提交...',
      mask: true
    })
    let baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      header = getApp().globalData.header,
      list = [],
      self = this,
      post_script = this.data.message ? this.data.message:'',
      address_id = this.data.data.address.id,
      coupon_id = this.data.coupon != -1 ? this.data.data.coupon.unused[this.data.coupon].coupon_id: '',
      integral = this.data.integral ? this.data.integral: ''
    this.data.data.list.forEach( value => {
      list.push(0)
      list.push(value.product_id)
      list.push(value.num)
      list.push(value.price)
      // list.push(value.coupon_id)
      // list.push(value.integral)
    })
    if (!address_id){
      wx.showToast({
        title: '请选择收货地址',
        image: '../../image/error.png'
      })
      return
    }
    wx.request({
      url: baseUrl + '/Order/show',
      method: 'POST',
      header,
      data: { access_token, list, post_script, address_id, coupon_id, integral},
      success: data => {
        wx.hideLoading()
        console.log(data.data)
        if(data.data.code == 200){
          // // 调用微信支付
          // wx.requestPayment({
          //   timeStamp: data.data.data.timeStamp,
          //   nonceStr: data.data.data.nonceStr,
          //   package: data.data.data.package,
          //   signType: data.data.data.signType,
          //   paySign: data.data.data.paySign,
          //   success: res => {
          //       wx.showToast({
          //         title: '支付成功！',
          //         mask: true
          //       })
          //       setTimeout(function () {
          //         wx.redirectTo({
          //           url: '../my_order/my_order',
          //         })
          //       }, 1000)
          //   },
          //   fail: res => {
          //       wx.showToast({
          //         title: '支付失败',
          //         image: '../../image/error.png'
          //       })
          //       setTimeout(function(){
          //         wx.redirectTo({
          //           url: '../my_order/my_order',
          //         })
          //       },1000)
          //   }
          // })
          
          wx.navigateTo({
            url: '../my_order/my_order?active=1'
          })

        }
      }
    })
  },
  // 输入酒币
  integral(e){
    let integral = parseFloat(e.detail.value)
    let self = this
    // let new_integral_price = parseInt(this.data.data.integral_value * this.data.price * this.data.num - 1);
    let new_integral_price = parseInt(this.data.integral_price);
    console.log('pay_price的值相关',this.data)

    console.log('integral',integral)
    console.log('integral_price', this.data.data.integral_price)
    console.log(parseInt(integral) > parseInt(this.data.data.integral_price))
    if (parseInt(integral) > parseInt(new_integral_price)){
      this.setData({
        integral: new_integral_price,
        
      })
    }else{
      this.setData({
        integral: integral,
        
      })
    }
    this.getIntegralMoney(this.data.integral)

  },
  //计算输入酒币后抵多少钱
  getIntegralMoney(integral){
    let integral_value = Number(this.data.data.integral_value)
    integral = Number(this.data.integral)
    console.log('integral', integral)
    console.log('integral_value', integral_value)
    let money = parseFloat(integral / integral_value)
    money = Number(money).toFixed(2)
    console.log('money', money)
    // let cash = this.data.cash;
    let pay_price = (this.data.data.pay_price * 1 - money).toFixed(2);
    if (pay_price<=0){
      this.setData({
        money: money,
        pay_price: 0.01
      })
    }else{
      this.setData({
        money: money,
        pay_price: pay_price
      })
    }
  },
  // 选择优惠券
  showCoupon(){
      var arr = this.data.data.coupon.unused.map(value => {
        return value.card_name
      })
      arr.push('不使用优惠劵')
    // let cash = this.data.coupon == -1 ? '' : Number(this.data.data.coupon.unused[this.data.coupon].cash)
    let self = this
    wx.showActionSheet({
      itemList: arr || "点击选择优惠劵",
      success: res => {
        console.log(res)
        console.log(res.tapIndex)
        if (res.tapIndex == arr.length - 1) {
          self.setData({
            coupon_id: -1,
            itemList: "点击选择优惠劵",
            coupon: -1
          })
          if (self.data.options.isBuyNow == 'true') {
            self.buy_now(self.data.options.price, self.data.options.product_id);
          } else {
            self.buy_cart(self.data.options.num, self.data.options.check, self.data.options.car_id)
          }
          return
        }
        if (res.hasOwnProperty('tapIndex')){
          self.setData({
            coupon: res.tapIndex,
            coupon_id: self.data.data.coupon.unused[res.tapIndex].coupon_id
          })

          if (self.data.options.isBuyNow == 'true'){
            self.buy_now(self.data.options.price, self.data.options.product_id);
          }else{
            self.buy_cart(self.data.options.num, self.data.options.check, self.data.options.car_id)
          }

        }
      },
      fail: function (res) {
        // cosole.log(res.errMsg)
        self.setData({
          itemList: "点击选择优惠劵"
          // coupon_id: -1
        })
      }
    })
    // this.getPayPrice(this.data.cash)
  },
  //求总计
  // getPayPrice(cash){
  //   cash = this.data.cash;
  //   let mon= this.data.money;
  //   let pay_price  = (this.data.pay_price - cash - mon).toFixed(2)

  //   if (pay_price<=0){  
  //     this.setData({
  //         pay_price:0.01
  //       })
  //   }else{
  //     this.setData({
  //       pay_price: pay_price
  //     })
  //   }
  // },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let options = this.data.options
    if (options.isBuyNow) {
      var price = options.price,
        product_id = options.product_id
      let self = this
      if (!getApp().globalData.access_token) {
        getApp().setUser(function () {
          return self.buy_now(price, product_id)
        })
      } else {
        self.buy_now(price, product_id)
      }
    }
    
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }

})